<template>
  <div class="content">
    <div class="pageSearchView" style="display: flex; justify-content: space-between; align-items: center;">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="计划号">
          <el-input v-model="searchParam.planNo" placeholder="请输入计划号" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="产出物料">
          <el-input v-model="searchParam.productNo" placeholder="请输入产出物料" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="生产数量">
          <el-input disabled v-model="searchParam.planCount" placeholder="请输入生产数量" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="计划时间">
          <el-date-picker disabled v-model="searchParam.times" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
                          range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" style="width: 400px;"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="selGetList()">查询</el-button>
          <el-button style="margin-top: -1%;" :icon="Refresh"
                     @click="resetSearch()">重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-button style="margin-top: -1%;" :icon="Reading" :disabled="!searchParam.planNo"
                 @click="showDialog()">详情
      </el-button>
    </div>
    <div class="pageTableView" v-if="paginatedData.length > 0">
      <div class="leftView">
        <div class="nodeList" v-for="(item, index) of paginatedData" :key="index"
             :class="index == tabIndex ? 'boxShow' : ''" @click="leftChange(index)">
          <!-- item.count > 0 ? 'yellowView' : 'greyView' -->
          <div class="nodeBody" :class="colorBg(item)">
            <div class="nodeTitle"> {{ item.procedureName }}</div>
            <div class="nodeInfo">
              <div> 计划数：<span>{{ item.planNumber || 0 }}</span></div>
              <div> 报工数：<span>{{ item.count || 0 }}</span></div>
              <div> 未完成：<span>{{ item.unFinishNumber || 0 }}</span></div>
            </div>
          </div>
        </div>
      </div>
      <div class="rightView">
        <el-tabs v-model="isWorkStatusTab" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="投料详情" name="false">
            <el-table :data="throwMaterialRecords" height="calc(100vh - 270px)" row-key="id" :stripe="false"
                      class="sort-el-table" header-cell-class-name="witheTableHeader">
              <el-table-column type="index" label="序号" width="80" align="center"/>
              <el-table-column prop="batchNo" label="批次号" align="center" min-width="150"/>
              <el-table-column prop="materialName" label="物料名称" align="center" min-width="200"
                               show-overflow-tooltip/>
              <el-table-column prop="materialCount" label="投料数量" align="center"/>
              <el-table-column prop="status" label="状态" width="150" align="center">
                <template #default="scope">
                  <span> {{ scope.row.status == true ? '退料' : '投料' }} </span></template>
              </el-table-column>
              <el-table-column prop="createTime" label="投料时间" align="center"/>
              <!--							<el-table-column prop="createUser" label="创建人" width="150" align="center" />-->
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="报工详情" name="true">
            <el-table :data="reportWorkRecordVOS" height="calc(100vh - 270px)" row-key="id" :stripe="false"
                      class="sort-el-table" header-cell-class-name="witheTableHeader">
              <el-table-column type="index" label="序号" width="80" align="center"/>
              <el-table-column prop="reportWorkRecordNo" label="批次号" align="center" min-width="160"/>
              <el-table-column prop="materialOutName" label="产出物料" align="center" min-width="220"/>
              <el-table-column prop="reportTraceCode" label="追溯码" align="center" min-width="210"/>
              <el-table-column prop="count" label="报工数量" align="center" width="150"/>
              <el-table-column prop="status" label="物料状态" :formatter="statusType" align="center"/>
              <el-table-column prop="reportTime" label="报工时间" align="center" min-width="180" sortable/>
              <!--							<el-table-column prop="createUser" label="创建人" width="150" align="center" />-->
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="pageTableView" style="display: flex;justify-content: center;align-items: center;color: #777;"
         v-else> 暂无数据
    </div>
    <el-dialog v-model="dialogRef" title="计划详情" @close="onCloseButton" width="98%">
      <div class="dialog-content">
        <div ref="echartsContainer" style="width: 100%; height: 200px;"></div>
      </div>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCloseButton">关闭</el-button>
				</span>
      </template>
    </el-dialog>
    <el-dialog v-model="showCrud" title="计划产出" width="1000px">
      <el-table class="pageTableClass" :data="tableSearchOutput" height="calc(100vh - 600px)"
                row-key="id" @row-click="handleRowClick">
        <el-table-column prop="planNo" label="生产计划号" min-width="150"/>
        <el-table-column prop="productCode" label="产出物料编号" min-width="150"/>
        <el-table-column prop="productName" label="产出物料名称" min-width="150"/>
      </el-table>
      <div class="pagePagination">
        <el-pagination background layout="total,prev, pager, next" :total="OutputPageTotal"
                       :page-size="pageSearchOutput.pageSize"
                       :current-page="pageSearchOutput.current" @current-change="handleCurrentChange"/>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {ref, computed, watch, onMounted, nextTick} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {queryByPlanIdDetail} from '@/api/production/productionPlan';
import {
  Delete, Edit, Tickets, DocumentChecked
  , Search, Share, Upload, Refresh, Plus, DocumentCopy, Files, Reading
} from '@element-plus/icons-vue';
import axiosInstance from '@/utils/http/api';
import draggable from 'vuedraggable';
import {useRoute, useRouter} from 'vue-router';
import * as echarts from 'echarts';

const route = useRoute();
const searchParam = ref({});
const paginatedData = ref([]);
const OutputPageTotal = ref(0);
const isWorkStatusTab = ref('false');
const isWorkStatus = ref('false');
const dialogRef = ref(false);
const echartsContainer = ref(null);
const showCrud = ref(false);
const chartDom = ref({});
const pageSearch = ref({
  current: 1,
  pageSize: 10
});
const pageSearchOutput = ref({
  current: 1,
  pageSize: 10
});
const handleCurrentChange = (e) => {
  pageSearchOutput.value.current = e
  selGetList()
}
const tableSearchOutput = ref([])
const colorBg = (data) => {
  if (data.procedureOrderStatus === 0) {
    return 'greyView'
  } else if (data.procedureOrderStatus === 1) {
    return 'yellowView'
  } else if (data.procedureOrderStatus === 2) {
    return 'endView'
  } else if (data.procedureOrderStatus === 3) {
    return 'errView'
  }
}
const showDialog = () => {
  dialogRef.value = true;
  nextTick(() => {
    const chart = echarts.init(echartsContainer.value);
    queryByPlanIdDetail({planNo: searchParam.value.planNo}).then(res => {
      if (res.code == 200) {
        chartDom.value = res.data;
        var layerOneNumber = 0;
        res.data.children.forEach(item => {
          layerOneNumber += item.planCount;
        });
        const mockData = generateMockData([res.data], layerOneNumber);
        const {nodes, links} = mockData;

        const option = {
          tooltip: {
            trigger: 'item',
            triggerOn: 'mousemove',
            formatter: params => {
              // 自定义提示框显示的内容
              return params.name; // 仅显示 name
            }
          },
          series: {
            type: 'sankey',
            layout: 'none',
            nodeAlign: 'left',
            emphasis: {
              focus: 'adjacency'
            },
            data: nodes,
            links: links,
            lineStyle: {
              color: 'source',
              curveness: 0.5
            }
          }
        };

        chart.setOption(option);
      } else {
        chart.setOption(null);
      }
    })


  });
}
const generateMockData = (data, num) => {
  const nodes = [];
  const links = [];

  data?.map((item) => {
    const orderPlan = '计划号' + item.planNo;
    nodes.push({name: orderPlan});
    item.children.forEach((i) => {
      const orderPlan1 = '数量' + i.planCount + '产品' + i.productName;
      nodes.push({name: orderPlan1});
      links.push({source: orderPlan, target: orderPlan1, value: i.planCount});
      if (!i.children) {
        return;
      }
      i.children.map((s, index) => {
        const orderPlan2 = '数量' + s.orderCount + '工序订单' + s.no;
        const childValue = Math.round(i.planCount * (s.orderCount / (i.children.reduce((acc, curr) => acc + curr.orderCount, 0))));
        nodes.push({name: orderPlan2});
        links.push({source: orderPlan1, target: orderPlan2, value: childValue});
        if (s.children && s.factionWork) {
          if (s.factionWork.count !== 0) {
            const factionWorkValue = Math.round(childValue * (s.factionWork.count / s.orderCount));
            const orderPlan3 = '工序订单' + s.no;
            nodes.push({name: orderPlan3 + '未派工数量:' + s.factionWork.count});
            links.push({
              source: orderPlan2,
              target: orderPlan3 + '未派工数量:' + s.factionWork.count,
              orderPlan2,
              value: factionWorkValue
            });
          }

        } else {
          const orderPlan3 = '工序订单' + s.no;
          nodes.push({name: orderPlan3 + '未派工数量:' + s.orderCount});
          links.push({
            source: orderPlan2,
            target: orderPlan3 + '未派工数量:' + s.orderCount,
            orderPlan2,
            value: childValue
          });
        }
        if (!s.children) {
          return;
        }
        s.children.map((n) => {
          const factionWorkValues = Math.round(childValue * (n.orderCount / s.orderCount));
          const orderPlan3 = '数量' + n.orderCount + '工单' + n.workNo;

          nodes.push({name: orderPlan3});
          links.push({source: orderPlan2, target: orderPlan3, value: factionWorkValues});
        });
      });
    });
  });
  return {nodes, links};
};
const onCloseButton = () => {
  dialogRef.value = false;
};
const handleClick = (tab: TabsPaneContext, event: Event) => {
  isWorkStatus.value = tab.paneName;
  if (searchParam.value.id) {
    getList();
  }
};

const statusType = (e) => {
  const list = [{
    label: '不合格',
    value: '0'
  }, {
    label: '合格',
    value: '1'
  }, {
    label: '报废',
    value: '2'
  }];
  const type = list.find(type => type.value == e.status);
  return type ? type.label : '';
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};

};
// 获取列表
const getList = async () => {
  if (!searchParam.value.planNo) {
    ElMessage.error('请输入计划号')
    return false
  }
  paginatedData.value = [];
  axiosInstance.get('/api/throwMaterialRecord/queryAllPlanDetailById', {
    params: {
      planNo: searchParam.value.planNo,
    }
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        if (res.data.length == 0) {
          ElMessage.error('未查询到数据');
          return false;
        }

        let list = res.data;
        list.sort((a, b) => a.index - b.index);
        paginatedData.value = list;
        leftChange(0);
      });
};

const throwMaterialRecords = ref([]);
const reportWorkRecordVOS = ref([]);
const tabIndex = ref(0);
const leftChange = (index) => {
  tabIndex.value = index;
  if (paginatedData.value[index].throwMaterialRecords) {
    throwMaterialRecords.value = paginatedData.value[index].throwMaterialRecords;
  } else {
    throwMaterialRecords.value = [];
  }


  if (paginatedData.value[index].reportWorkRecordVOS) {
    reportWorkRecordVOS.value = paginatedData.value[index].reportWorkRecordVOS;
  } else {
    reportWorkRecordVOS.value = [];
  }

  console.log(reportWorkRecordVOS.value, 'reportWorkRecordVOS.valuereportWorkRecordVOS.value')
};
const selGetList = () => {

  axiosInstance.post('/api/planOrder/queryPlanByProduct', {
    planNo: searchParam.value.planNo || '',
    productNo: searchParam.value.productNo || '',
    ...pageSearchOutput.value,
  }).then(res => {
    const {records} = res.data
    if (records.length === 0) {
      searchParam.value.planCount = ''
      searchParam.value.times = ''
      return
    }
    if (records.length < 2) {
      selQueryPlan(records[0].id)
    } else {
      pageSearchOutput.value = {
        current: 1,
        pageSize: 10
      }
      showCrud.value = true
      tableSearchOutput.value = records
      OutputPageTotal.value = res.data.total
    }

  })
}
const selQueryPlan = (planId) => {
  axiosInstance.get('/api/planOrder/queryPlanData', {
    params: {planId}
  }).then(res => {
    searchParam.value.planNo = res?.data?.planNo
    searchParam.value.productNo = res?.data?.productCode
    searchParam.value.planCount = res?.data?.planCount
    searchParam.value.times = [res?.data?.planBeginTime, res?.data?.planEndTime]
    showCrud.value = false
    getList()
  })
}
const handleRowClick = (row) => {
  selQueryPlan(row.id)
  // 在这里添加你想要执行的逻辑
}
onMounted(() => {
  searchParam.value.planNo = route.query.planNo
  if (searchParam.value.planNo) {
    axiosInstance.get('/api/planOrder/queryPlanData', {
      params: {
        planId: route.query.planNoId,

      }
    }).then(res => {
      searchParam.value.productNo = res?.data?.productCode
      searchParam.value.planCount = res?.data?.planCount
      searchParam.value.times = [res?.data?.planBeginTime, res?.data?.planEndTime]
      getList()
    })

  }
});
</script>
<style scoped>
.leftView {
  height: 100%;
  width: 450px;
  overflow-y: auto;
}

.rightView {
  width: calc(100% - 451px);
  height: 100%;
  padding: 0 10px;
}

.pageTableView {
  height: calc(100vh - 190px);
  display: flex;
}


.nodeList {
  width: 420px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  margin: 10px 0 25px 0;
  user-select: none;
  border-radius: 15px;
  font-weight: bolder;
  cursor: pointer;
}

.nodeBody {
  border-radius: 5px;
  padding: 8px 10px;
}

.nodeTitle {
  width: 100%;
  padding: 15px 10px 5px 10px;
  font-weight: 700;
  border-radius: 10px 10px 0 0;
  font-weight: 700;
  font-size: 20px;
}

.yellowView {
  background-color: #C1D1FF;
  color: #555;
}

.greyView {
  background-color: #D1D1D1;
  color: #666;
}

.errView {
  background-color: #f00;
  color: #fff;
}

.endView {
  background-color: #65b9747a;
  color: #666;
}

.boxShow {
  box-shadow: 0 10px 14px 0 rgba(0, 20, 45, 0.2);
}

.nodeInfo {
  display: flex;
  padding: 10px;
  justify-content: space-between;
  color: #777;
  font-size: 15px;
}

.nodeInfo > div {
  width: 33%;
}


.nodeInfo > div > span {
  font-weight: 700;
}
</style>
